/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */
package com.hopes.bizz.emergency.plan.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopes.bizz.emergency.common.constant.PlanDicConstant;
import com.hopes.bizz.emergency.plan.dto.ErEmergencyPlanDTO;
import com.hopes.bizz.emergency.plan.entity.EpEmergencyPlanFileEntity;
import com.hopes.bizz.emergency.plan.entity.ErEmergencyPlanAuditRecordEntity;
import com.hopes.bizz.emergency.plan.entity.ErEmergencyPlanEntity;
import com.hopes.bizz.emergency.plan.mapper.ErEmergencyPlanMapper;
import com.hopes.bizz.emergency.plan.service.EpEmergencyPlanFileService;
import com.hopes.bizz.emergency.plan.service.ErEmergencyPlanAuditRecordService;
import com.hopes.bizz.emergency.plan.service.ErEmergencyPlanService;
import com.hopes.bizz.emergency.plan.vo.ErEmergencyPlanVO;
import com.hopes.boss.common.core.util.R;
import com.hopes.boss.common.security.util.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 企业应急预案
 *
 * @author cx
 * @date 2023-10-26 11:07:16
 */
@Service
public class ErEmergencyPlanServiceImpl extends ServiceImpl<ErEmergencyPlanMapper, ErEmergencyPlanEntity> implements ErEmergencyPlanService {

    @Resource
    private ErEmergencyPlanAuditRecordService erEmergencyPlanAuditRecordService;


    @Resource
    private EpEmergencyPlanFileService epEmergencyPlanFileService;
    @Override
    public void handlerAudit(ErEmergencyPlanEntity erEmergencyPlan) {
        //选择的状态
        Integer preStatus = erEmergencyPlan.getPlanState();
        UpdateWrapper<ErEmergencyPlanEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(ErEmergencyPlanEntity::getId, erEmergencyPlan.getId())
                .set(ErEmergencyPlanEntity::getPlanState, preStatus);
        if (PlanDicConstant.EMERGENCY_STATUS_WAIT_RELEASE.equals(preStatus)
                || PlanDicConstant.EMERGENCY_STATUS_AUDIT_FAILED.equals(preStatus)
                || PlanDicConstant.EMERGENCY_STATUS_ALREADY_RELEASE.equals(preStatus)) {
            updateWrapper.lambda().set(ErEmergencyPlanEntity::getAuditOpinion, erEmergencyPlan.getAuditOpinion());
            ErEmergencyPlanAuditRecordEntity recordEntity = new ErEmergencyPlanAuditRecordEntity();
            recordEntity.setEmergencyPlanId(erEmergencyPlan.getId());
            recordEntity.setAuditStatus(preStatus);
            recordEntity.setAuditOpinion(erEmergencyPlan.getAuditOpinion());
            recordEntity.setAuditUser(SecurityUtils.getUser().getName());
            recordEntity.setCreateUserId(SecurityUtils.getUserId());
            erEmergencyPlanAuditRecordService.save(recordEntity);
        }
        this.update(updateWrapper);
    }

    @Override
    public R getPlanOverviewPage(Page<ErEmergencyPlanEntity> page) {
        IPage<ErEmergencyPlanEntity> iPage = this.page(page, Wrappers.<ErEmergencyPlanEntity>lambdaQuery()
                .isNotNull(ErEmergencyPlanEntity::getPlanType)
                .eq(SecurityUtils.isCompany(), ErEmergencyPlanEntity::getOrgId, SecurityUtils.getOrgId())
                .select(ErEmergencyPlanEntity::getId, ErEmergencyPlanEntity::getPlanType,ErEmergencyPlanEntity::getOrgId));

        Map<Long, ErEmergencyPlanVO> resultMap = new HashMap<>();
        for (ErEmergencyPlanEntity plan : iPage.getRecords()) {
            Long orgId = plan.getOrgId();
            if (!resultMap.containsKey(orgId)) {
                ErEmergencyPlanVO vo = new ErEmergencyPlanVO();
                vo.setOrgId(orgId);
                // 初始化计数器Map
                vo.setPlanTypeCounts(new HashMap<>());
                resultMap.put(orgId, vo);
            }
            ErEmergencyPlanVO vo = resultMap.get(orgId);
            // 总数加一
            vo.setTotalPlans(Objects.requireNonNullElse(vo.getTotalPlans(), 0L) + 1);
            Integer planType = plan.getPlanType();
            vo.getPlanTypeCounts().put(planType, vo.getPlanTypeCounts().getOrDefault(planType, 0L) + 1);
        }

        List<ErEmergencyPlanVO> resultList = new ArrayList<>(resultMap.values());
        Page<ErEmergencyPlanVO> resultPage = new Page<>();
        resultPage.setRecords(resultList);
        resultPage.setCurrent(iPage.getCurrent());
        resultPage.setSize(iPage.getSize());
        resultPage.setTotal(iPage.getTotal());

        return R.ok(resultPage);
    }

    @Override
    public Object saveEnterprise(ErEmergencyPlanDTO erEmergencyPlan) {
        ErEmergencyPlanEntity erEmergencyPlanEntity = new ErEmergencyPlanEntity();
        BeanUtils.copyProperties(erEmergencyPlan,erEmergencyPlanEntity);
        this.save(erEmergencyPlanEntity);
        List<EpEmergencyPlanFileEntity> fileList = erEmergencyPlan.getFileList();
        fileList.forEach(fileEntity -> fileEntity.setEmergencyPlanId(erEmergencyPlanEntity.getId()));
        return epEmergencyPlanFileService.saveFile(fileList);
    }

    @Override
    public Object updateEnterprise(ErEmergencyPlanDTO erEmergencyPlan) {
        ErEmergencyPlanEntity erEmergencyPlanEntity = new ErEmergencyPlanEntity();
        BeanUtils.copyProperties(erEmergencyPlan, erEmergencyPlanEntity);
        this.updateById(erEmergencyPlanEntity);
        List<EpEmergencyPlanFileEntity> fileList = erEmergencyPlan.getFileList();
        fileList.forEach(fileEntity -> fileEntity.setEmergencyPlanId(erEmergencyPlanEntity.getId()));
        return epEmergencyPlanFileService.updateFile(fileList);
    }
}